package com.base.essearch.video.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.essearch.es.service.IMovieService;
import com.base.essearch.utils.StringUtils;
import com.base.essearch.video.entity.VideoMediaFile;
import com.base.essearch.video.mapper.VideoMediaFileMapper;
import com.base.essearch.video.service.IVideoMediaFileService;
import com.base.essearch.webupload.entity.FileRecord;
import com.base.essearch.webupload.service.IFileRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lr
 * @since 2020-12-06
 */
@Service
public class VideoMediaFileServiceImpl extends ServiceImpl<VideoMediaFileMapper, VideoMediaFile> implements IVideoMediaFileService {

    @Autowired
    private IFileRecordService fileRecordService;
    @Autowired
    private VideoMediaFileMapper videoMediaFileMapper;

    @Override
    public void saveToEs(VideoMediaFile mediaFile, FileRecord fileRecord) {
        // 上传到七牛云
        fileRecordService.uploadM3u8FileToQiNiu(mediaFile, fileRecord);
    }

    @Override
    public VideoMediaFile getFileById(String file) {
        VideoMediaFile byId = this.getById(file);
        List<FileRecord> fileRecords = fileRecordService.list(Wrappers.<FileRecord>lambdaQuery()
                .in(FileRecord::getMd5Value, file)
        );
        if (CollectionUtils.isNotEmpty(fileRecords)) {
            FileRecord fileRecord = fileRecords.get(0);
            byId.setFileRecord(fileRecord);
            if (fileRecord.getSearchKey() == null) {
                fileRecord.setSearchKey(fileRecord.getOrgName());
            }
            if (StringUtils.isNotBlank(fileRecord.getImgId())) {
                List<FileRecord> fileRecords1 = fileRecordService.listByIds(Arrays.asList(fileRecord.getImgId()));
                if (CollectionUtils.isNotEmpty(fileRecords1)) {
                    List<String> collect = fileRecords1.stream().map(FileRecord::getNetworkPath).collect(Collectors.toList());
                    byId.setImage(collect.get(0));
                    byId.setImages(collect);
                }
            }
        }
        return byId;
    }

    @Override
    public VideoMediaFile getnext(String fileId) {
        return videoMediaFileMapper.selectNext(fileId);
    }

    @Override
    public VideoMediaFile getpre(String fileId) {
        return videoMediaFileMapper.selectPre(fileId);
    }

    @Override
    public VideoMediaFile getnextlast(String fileId) {
        return videoMediaFileMapper.selectNextLast(fileId);
    }

    @Override
    public VideoMediaFile getprelast(String fileId) {
        return videoMediaFileMapper.selectPreLast(fileId);
    }
}
